import * as uuid from 'uuid';
import * as fs from 'fs-extra';
import csvjson from 'csvjson';
import moment from "moment";
import {configurationService} from "./configService";

function getEnv(name) {
  return process.env[name];
}

const userId = configurationService.config.envConfig.userId//getEnv('SP_USER_ID');
const appId = configurationService.config.envConfig.appId//getEnv('SP_APP_ID');
const nodeId = configurationService.config.envConfig.nodeId//getEnv('SP_NODE_ID');

export let gatewayEndpoint;

gatewayEndpoint = configurationService.config.gatewayConfig?.endpoint || 'http://sim-gateway.default:7777';

export enum products {
  ABAQUS = 'abaqus',
  SOLIDWORKS = 'solidworks',
  META = 'meta',
  HYPERMESH = 'hypermesh',
  NASTRAN = 'nastran',
  CAX = 'cax',
  MULTI_SOLVERS = 'multiSolvers'
}

export function getNodeId(): string {
  return nodeId;
}

export const generateUUID = () => {
  return uuid.v4();
};

export function isDesktop(): boolean {
  return !!process.env.SP_DESKTOP_HOME;
}

export function convertToUnixPath(path: string): string {
  return path.replace(/\\/g, '/');
}

export function randomNum(minNum: number, maxNum: number) {
  switch (arguments.length) {
    case 1:
      return parseInt(`${Math.random() * minNum + 1}`);
    case 2:
      return parseInt(`${Math.random() * (maxNum - minNum + 1) + minNum}`);
    default:
      return 0;
  }
}

export function generateBusinessId() {
  return `sim_${Date.now()}` + randomNum(100, 999);
}

export function isNumberic(num: any) {
  return (typeof (num) === 'number' || typeof (num) === 'string' && num.trim() !== '') && !isNaN(num as number);
}

export function getOSSSimulationConfigFilePath() {
  return `studio/simulation/configs/${userId}/${appId}/${nodeId}/simConfig.json`;
}

export function getOSSSimulationProjectFilePath() {
  return `studio/simulation/project/${userId}/${nodeId}`;
}

export function getOSSSimulationParameterFilePath() {
  return `studio/simulation/parameter/${moment().format('yyyyMMDDHHmmss')}`;
}

export function getOssAgentPath() {
  return 'studio/simulation/agent/sim-agent-latest.exe';
}


export function getOnlineAgent(product: string) {
  const agentsApi = `${gatewayEndpoint}/api/agents/${product}/online`;
  return agentsApi;
}

export function getGatewayJobsPageApi() {
  const jobsApi = `${gatewayEndpoint}/api/jobs/page/${userId}/${appId}/${nodeId}`;
  return jobsApi;
}

export function getGatewayJobStopApi(businessId: string) {
  const jobStopApi = `${gatewayEndpoint}/api/job/stop/${userId}/${appId}/${nodeId}/${businessId}`;
  return jobStopApi;
}

export function getGatewayJobStopApiByJobId(jobId: string) {
  const jobStopApi = `${gatewayEndpoint}/api/job/stop/${jobId}`;
  return jobStopApi;
}

export function getGatewayParamValidApi() {
  const paramValidApi = `${gatewayEndpoint}/api/param/valid`;
  return paramValidApi;
}

export function getGatewayParseModelTreesApi() {
  const modelFileApi = `${gatewayEndpoint}/api/model/file/trees`;
  return modelFileApi;
}

export function getGatewayParseModelParamsApi() {
  const parseModelParamApi = `${gatewayEndpoint}/api/model/parse/param`;
  return parseModelParamApi;
}

export function getGatewayDeleteJobApi(businessId: string) {
  const jobDeleteApi = `${gatewayEndpoint}/api/job/delete/${userId}/${appId}/${nodeId}/${businessId}`;
  return jobDeleteApi;
}

export function getGatewayPauseJobApi(businessId: string) {
  const jobPauseApi = `${gatewayEndpoint}/api/job/pause/${userId}/${appId}/${nodeId}/${businessId}`;
  return jobPauseApi;
}

export function getGatewayDeleteJobBatchApi() {
  return `${gatewayEndpoint}/api/job/delete/batch/${userId}/${appId}/${nodeId}`;
}

export function getGatewayDeleteJobBatchByJobIdApi() {
  return `${gatewayEndpoint}/api/job/delete/batch`;
}

export function getCheckAgentApi() {
  const api = `${gatewayEndpoint}/api/agent/check`;
  return api;
}

export function getSimJobRetry(businessId: string) {
  return `${gatewayEndpoint}/api/job/retry/${userId}/${appId}/${nodeId}/${businessId}`;
}

export function getSimJobRetryByJobId(jobId: string) {
  return `${gatewayEndpoint}/api/job/retry/${jobId}`;
}

export function getJobLogPath(jobId: string) {
  return `studio/${userId}/simulation/logs/${jobId}.log`;
}

export function getSimSyncPath(jobId: string) {
  return `studio/${userId}/simulation/sync/${jobId}/`;
}

export function getAgentPage() {
  return  `${gatewayEndpoint}/api/agents`;
}

export function getProductPage() {
  return  `${gatewayEndpoint}/api/products/page`;
}

export function getProduct() {
  return  `${gatewayEndpoint}/api/product`;
}

export function getGatewayMultiJobApi() {
  return  `${gatewayEndpoint}/api/jobs/multiJob`;
}

export function getGatewayMultiJobDetailApi(jobId: string) {
  return `${gatewayEndpoint}/api/multiJob/${jobId}`;
}

export function getGatewayMultiJobAllInfoApi(businessId: string) {
  return  `${gatewayEndpoint}/api/multiJob/detail/${businessId}`;
}

export function getTimeLeft2BySecond(s: number): string {
  let hours = Math.round((s - 30 * 60) / (60 * 60));
  let minutes = Math.round((s - 30) / 60) % 60;
  let seconds = Math.floor(s % 60);
  return (hours > 0 ? (hours + '小时') : '') + (minutes > 0 ? (minutes + '分钟') : '') + (seconds > 0 ? (seconds + '秒') : '');
}

export function transferArray2Csv(data: any[], filePath: string) {
  if (!fs.existsSync(filePath)) {
    fs.ensureFileSync(filePath);
  }
  const writeStream = fs.createWriteStream(filePath);
  data.forEach(d => {
    writeStream.write(`${d.join(',')}\n`);
  });
  writeStream.close();
}

export function transferJson2Csv(jsonStr: string, filePath: string) {
  let options = {
    delimiter: ',',
    wrap: false,
    headers: 'key'
  };
  const data = csvjson.toCSV(jsonStr, options);
  if (!fs.existsSync(filePath)) {
    fs.ensureFileSync(filePath);
  }
  fs.writeFileSync(filePath, data);
}

